var nrc = require('node-run-cmd');
const timeUtil = require('../util/TimeUtils')

let data = [
    {
        "name":"OtherCity",
        "input": "D:/hls_genrate/my_genrator/small_other.mp4",
        "output": "D:/hls_genrate/my_genrator/out/temp1/",
        "duration": 60.000000
    },
    {
        "name":"地球百子",
        "input": "D:/hls_genrate/my_genrator/small_baizi.mp4",
        "output": "D:/hls_genrate/my_genrator/out/temp2/",
        "duration": 60.000000
    },
    {
        "name":"测试视频",
        "input": "D:/hls_genrate/my_genrator/output.mp4",
        "output": "D:/hls_genrate/my_genrator/out/temp3/",
        "duration": 60.000000
    }
];
let water_mark = {
    x: 100,
    y: 80,
    s: 80
}
let water_scale = parseInt(255 / 100 * water_mark.s) + ":" + parseInt(80 / 100 * water_mark.s);
let extra = "-b:v 192k -b:a 128k -r 24";

const queue = require('fastq')(worker, 2)

data.forEach(function (res) {
    queue.push(res, function (err, result) {
        if (err) {
            throw err
        }
        console.log('线程完成: ', result)
    })
})

function worker(arg, cb) {
    let filePath = arg['input'];
    let out = arg['output'];
    let duration = arg['duration']
    let name = arg['name']

    let cmd = 'ffmpeg -y -i ' + filePath + ' -vf "movie=../../static/Watermark.png, scale=' + water_scale + ' [watermark]; [in][watermark] overlay=' + water_mark.x + ':' + water_mark.y + '[out]" -sc_threshold 0 -movflags frag_keyframe+empty_moov+default_base_moof -hls_time 8 -hls_playlist_type vod -hls_segment_type fmp4 ' + extra + " -c:v hevc -tag:v hvc1 -preset:v ultrafast -hls_segment_filename " + out + "/%4d.m4s " + out + "/index.m3u8";

    function callback(data) {
        var reg = /time=(.+) bitrate/;
        let result = reg.exec(data);
        if (result && result.length > 1) {
            let curTime = result[1];

            let per = timeUtil.getTime2Percent(duration, curTime);
            console.log(name+": "+per + "%");
            if (per>=100){
                cb(null, name)
            }
        } else {
            // console.log(data)
        }
    }
    nrc.run(cmd, {onData: callback, onError: callback});
}

